<template>
  <div class="sidepanel-container">
    <a-layout class="layout">
      <!-- 头部 -->
      <a-layout-header class="header">
        <div class="header-content">
          <h1 class="title">提示词管理</h1>
          <div class="header-actions">
            <a-button type="default" size="small" @click="handleImport" class="action-btn">
              <template #icon>
                <UploadOutlined />
              </template>
              导入
            </a-button>
            <a-button type="default" size="small" @click="handleExport" class="action-btn">
              <template #icon>
                <DownloadOutlined />
              </template>
              导出
            </a-button>
            <a-button type="primary" size="small" @click="showAddModal = true" class="add-btn">
              <template #icon>
                <PlusOutlined />
              </template>
              新增
            </a-button>
          </div>
        </div>
        <div class="search-bar">
          <a-input-search v-model:value="searchQuery" placeholder="搜索提示词..." @search="handleSearch"
            class="search-input" />
        </div>
      </a-layout-header>

      <!-- 内容区域 -->
      <a-layout-content class="content">
        <!-- 分类标签 -->
        <div class="category-tabs">
          <a-tag v-for="category in categories" :key="category.id"
            :color="activeCategory === category.id ? 'blue' : 'default'" class="category-tag"
            @click="setActiveCategory(category.id)">
            {{ category.name }} ({{ getPromptCountByCategory(category.id) }})
          </a-tag>
          <a-tag :color="activeCategory === null ? 'blue' : 'default'" class="category-tag"
            @click="setActiveCategory(null)">
            全部 ({{ prompts.length }})
          </a-tag>
        </div>

        <!-- 提示词列表 -->
        <div class="prompts-list">
          <a-empty v-if="filteredPrompts.length === 0" description="暂无提示词" />
          <div v-for="prompt in filteredPrompts" :key="prompt.id" class="prompt-card" @click="selectPrompt(prompt)"
            @dblclick="usePrompt(prompt)">
            <div class="prompt-header">
              <h3 class="prompt-title">{{ prompt.title }}</h3>
              <div class="prompt-actions">
                <a-tooltip title="复制">
                  <a-button type="text" size="small" @click.stop="copyPrompt(prompt)">
                    <template #icon>
                      <CopyOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip title="编辑">
                  <a-button type="text" size="small" @click.stop="editPrompt(prompt)">
                    <template #icon>
                      <EditOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip title="删除">
                  <a-button type="text" size="small" danger @click.stop="deletePrompt(prompt)">
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </div>
            </div>
            <p class="prompt-content">{{ truncateText(prompt.content, 100) }}</p>
            <div class="prompt-meta">
              <a-tag size="small" color="geekblue">{{ getCategoryName(prompt.category) }}</a-tag>
              <a-tag v-if="prompt.shortcut" size="small" color="orange">{{ prompt.shortcut }}</a-tag>
              <a-tag v-if="prompt.variables && prompt.variables.length > 0" size="small" color="green">
                变量: {{ prompt.variables.join(', ') }}
              </a-tag>
            </div>
          </div>
        </div>
      </a-layout-content>

      <!-- 底部 -->
      <a-layout-footer class="footer">
        <div class="footer-content">
          <a-button type="link" size="small" @click="showSettingsModal = true">
            <template #icon>
              <SettingOutlined />
            </template>
            设置
          </a-button>
          <span class="shortcut-hint">快捷键: {{ settings.shortcutKey }}</span>
        </div>
      </a-layout-footer>
    </a-layout>

    <!-- 新增/编辑提示词模态框 -->
    <a-modal v-model:open="showAddModal" :title="editingPrompt ? '编辑提示词' : '新增提示词'" @ok="handleSavePrompt"
      @cancel="handleCancelEdit" width="600px" :confirmLoading="saving" :destroyOnClose="false">
      <a-form ref="promptFormRef" :model="promptForm" :rules="promptFormRules" layout="vertical">
        <a-form-item label="标题" name="title">
          <a-input v-model:value="promptForm.title" placeholder="请输入提示词标题" />
        </a-form-item>

        <a-form-item label="内容" name="content">
          <a-textarea v-model:value="promptForm.content" placeholder="请输入提示词内容，使用 ${变量名} 格式定义变量" :rows="6"
            @change="handleContentChange" />
        </a-form-item>

        <a-form-item label="分类" name="category">
          <a-select v-model:value="promptForm.category" placeholder="选择分类">
            <a-select-option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="快捷短语" name="shortcut">
          <a-input v-model:value="promptForm.shortcut" placeholder="以 / 开头，如: /hello" @change="handleShortcutChange" />
        </a-form-item>

        <a-form-item v-if="detectedVariables.length > 0" label="检测到的变量">
          <div class="variables-preview">
            <a-tag v-for="variable in detectedVariables" :key="variable" color="blue">
              {{ variable }}
            </a-tag>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 变量输入模态框 -->
    <a-modal v-model:open="showVariableModal" title="填写变量" @ok="handleVariableSubmit"
      @cancel="showVariableModal = false" width="400px">
      <a-form layout="vertical">
        <a-form-item v-for="variable in currentVariables" :key="variable.name" :label="variable.name">
          <a-input v-model:value="variable.value" :placeholder="variable.placeholder" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 设置模态框 -->
    <a-modal v-model:open="showSettingsModal" title="设置" @ok="handleSaveSettings" @cancel="showSettingsModal = false"
      width="500px">
      <a-form layout="vertical">
        <a-form-item label="自动替换">
          <a-switch v-model:checked="settingsForm.autoReplace" />
          <div class="settings-hint">启用后，双击 Ctrl 键可快速替换快捷短语</div>
        </a-form-item>

        <a-form-item label="双击间隔 (毫秒)">
          <a-input-number v-model:value="settingsForm.doubleCtrlDelay" :min="100" :max="1000" :step="50" />
        </a-form-item>
      </a-form>

      <a-divider>分类管理</a-divider>

      <div class="category-management">
        <div class="category-list">
          <div v-for="category in categories" :key="category.id" class="category-item">
            <span>{{ category.name }}</span>
            <a-button v-if="category.id !== 'general'" type="text" size="small" danger
              @click="deleteCategory(category.id)">
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </div>
        </div>

        <div class="add-category">
          <a-input v-model:value="newCategoryName" placeholder="新分类名称" @keyup.enter="addCategory" />
          <a-button type="primary" @click="addCategory">添加分类</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 隐藏的文件输入 -->
    <input ref="fileInputRef" type="file" accept=".json" @change="handleFileSelect" style="display: none;" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import {
  PlusOutlined,
  CopyOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  UploadOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';
import { StorageManager } from '@/utils/storage';
import { extractVariables, replaceVariables } from '@/utils/variables';
import type { Prompt, Category, StorageData, VariableInput } from '@/types';

// 响应式数据
const prompts = ref<Prompt[]>([]);
const categories = ref<Category[]>([]);
const settings = ref<StorageData['settings']>({
  shortcutKey: 'Ctrl+Shift+P',
  autoReplace: true,
  doubleCtrlDelay: 300
});

const searchQuery = ref('');
const activeCategory = ref<string | null>(null);
const selectedPrompt = ref<Prompt | null>(null);

// 模态框状态
const showAddModal = ref(false);
const showVariableModal = ref(false);
const showSettingsModal = ref(false);
const saving = ref(false);

// 表单数据
const promptForm = ref({
  title: '',
  content: '',
  category: '',
  shortcut: ''
});

const settingsForm = ref({
  autoReplace: true,
  doubleCtrlDelay: 300
});

const newCategoryName = ref('');
const editingPrompt = ref<Prompt | null>(null);
const detectedVariables = ref<string[]>([]);
const currentVariables = ref<VariableInput[]>([]);
const promptFormRef = ref();
const fileInputRef = ref();

// 表单验证规则
const promptFormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
};

// 计算属性
const filteredPrompts = computed(() => {
  let filtered = prompts.value;

  // 按分类过滤
  if (activeCategory.value) {
    filtered = filtered.filter(p => p.category === activeCategory.value);
  }

  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(p =>
      p.title.toLowerCase().includes(query) ||
      p.content.toLowerCase().includes(query)
    );
  }

  return filtered;
});

// 方法
const loadData = async () => {
  try {
    const data = await StorageManager.getAll();
    prompts.value = data.prompts;
    categories.value = data.categories;
    settings.value = { ...settings.value, ...data.settings };
    settingsForm.value = {
      autoReplace: data.settings.autoReplace,
      doubleCtrlDelay: data.settings.doubleCtrlDelay
    };
  } catch (error) {
    console.error('加载数据失败:', error);
    message.error('加载数据失败');
  }
};

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

const setActiveCategory = (categoryId: string | null) => {
  activeCategory.value = categoryId;
};

const getPromptCountByCategory = (categoryId: string) => {
  return prompts.value.filter(p => p.category === categoryId).length;
};

const getCategoryName = (categoryId: string) => {
  const category = categories.value.find(c => c.id === categoryId);
  return category ? category.name : '未分类';
};

const selectPrompt = (prompt: Prompt) => {
  selectedPrompt.value = prompt;
};

const usePrompt = async (prompt: Prompt) => {
  try {
    const variables = extractVariables(prompt.content);

    if (variables.length > 0) {
      // 显示变量输入模态框
      currentVariables.value = variables.map(name => ({
        name,
        value: '',
        placeholder: `请输入 ${name} 的值`
      }));
      showVariableModal.value = true;

      // 聚焦第一个输入框
      await nextTick();
      const firstInput = document.querySelector('.ant-input') as HTMLInputElement;
      if (firstInput) {
        firstInput.focus();
      }
    } else {
      // 直接插入到当前活动标签页
      await insertToActivePage(prompt.content);
    }
  } catch (error) {
    console.error('使用提示词失败:', error);
    message.error('使用提示词失败');
  }
};

const insertToActivePage = async (text: string) => {
  try {
    // 获取当前活动标签页
    const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
    if (tab.id) {
      // 向内容脚本发送消息插入文本
      await browser.tabs.sendMessage(tab.id, {
        type: 'INSERT_TEXT',
        text: text
      });
      message.success('已插入提示词');
    }
  } catch (error) {
    console.error('插入文本失败:', error);
    // 如果内容脚本未注入，则复制到剪贴板
    await copyToClipboard(text);
    message.info('已复制到剪贴板，请手动粘贴');
  }
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
  } catch (error) {
    console.error('复制失败:', error);
    throw error;
  }
};

const copyPrompt = async (prompt: Prompt) => {
  try {
    await copyToClipboard(prompt.content);
    message.success('已复制到剪贴板');
  } catch (error) {
    message.error('复制失败');
  }
};

const editPrompt = async (prompt: Prompt) => {
  editingPrompt.value = prompt;

  // 使用 nextTick 确保在 DOM 更新后设置表单数据
  await nextTick();

  // 重新设置表单数据
  promptForm.value = {
    title: prompt.title,
    content: prompt.content,
    category: prompt.category,
    shortcut: prompt.shortcut || ''
  };

  detectedVariables.value = extractVariables(prompt.content);
  showAddModal.value = true;

  // 确保表单重新渲染后再次设置数据
  await nextTick();
  if (promptFormRef.value) {
    promptFormRef.value.clearValidate();
  }
};

const deletePrompt = (prompt: Prompt) => {
  Modal.confirm({
    title: '删除确认',
    content: `确定要删除提示词 "${prompt.title}" 吗？`,
    onOk: async () => {
      try {
        await StorageManager.deletePrompt(prompt.id);
        await loadData();
        message.success('删除成功');
      } catch (error) {
        console.error('删除失败:', error);
        message.error('删除失败');
      }
    },
    onCancel: () => {
      // 用户取消删除，无需操作
    }
  });
};

const handleSavePrompt = async () => {
  try {
    // 验证表单
    if (promptFormRef.value) {
      await promptFormRef.value.validate();
    }

    saving.value = true;

    const variables = extractVariables(promptForm.value.content);
    const promptData = {
      ...promptForm.value,
      variables,
      updatedAt: Date.now()
    };

    if (editingPrompt.value) {
      // 更新现有提示词
      await StorageManager.updatePrompt(editingPrompt.value.id, promptData);
      message.success('更新成功');
    } else {
      // 创建新提示词
      await StorageManager.addPrompt(promptData);
      message.success('添加成功');
    }

    await loadData();
    handleCancelEdit();
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const handleCancelEdit = () => {
  showAddModal.value = false;
  editingPrompt.value = null;
  promptForm.value = {
    title: '',
    content: '',
    category: '',
    shortcut: ''
  };
  detectedVariables.value = [];

  // 清除表单验证
  if (promptFormRef.value) {
    promptFormRef.value.clearValidate();
  }
};

const handleContentChange = () => {
  detectedVariables.value = extractVariables(promptForm.value.content);
};

const handleShortcutChange = () => {
  // 确保快捷短语以 / 开头
  if (promptForm.value.shortcut && !promptForm.value.shortcut.startsWith('/')) {
    promptForm.value.shortcut = '/' + promptForm.value.shortcut;
  }
};

const handleVariableSubmit = async () => {
  try {
    if (selectedPrompt.value) {
      const finalContent = replaceVariables(selectedPrompt.value.content, currentVariables.value);

      // 检查是否是快捷短语替换
      const replaceInfo = (selectedPrompt.value as any).replaceInfo;
      if (replaceInfo) {
        // 发送替换消息到 content script
        browser.runtime.sendMessage({
          type: 'REPLACE_TEXT',
          data: {
            startPos: replaceInfo.startPos,
            endPos: replaceInfo.endPos,
            text: finalContent
          }
        });
        message.success('已替换快捷短语');
      } else {
        // 正常插入
        await insertToActivePage(finalContent);
      }
    }
    showVariableModal.value = false;
    currentVariables.value = [];
    selectedPrompt.value = null;
  } catch (error) {
    console.error('插入提示词失败:', error);
    message.error('插入失败');
  }
};

const handleSaveSettings = async () => {
  try {
    const updatedSettings = {
      ...settings.value,
      ...settingsForm.value
    };
    await StorageManager.updateSettings(updatedSettings);
    settings.value = updatedSettings;
    showSettingsModal.value = false;
    message.success('设置已保存');
  } catch (error) {
    console.error('保存设置失败:', error);
    message.error('保存设置失败');
  }
};

// 导入功能
const handleImport = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
};

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  if (!file.name.endsWith('.json')) {
    message.error('请选择JSON文件');
    return;
  }

  try {
    const text = await file.text();
    const data = JSON.parse(text);

    // 验证数据格式
    if (!data.prompts || !Array.isArray(data.prompts)) {
      message.error('JSON文件格式不正确，缺少prompts数组');
      return;
    }

    if (!data.categories || !Array.isArray(data.categories)) {
      message.error('JSON文件格式不正确，缺少categories数组');
      return;
    }

    // 导入数据
    await StorageManager.importData(data);
    await loadData();
    message.success('导入成功');

    // 清空文件输入
    target.value = '';
  } catch (error) {
    console.error('导入失败:', error);
    message.error('导入失败，请检查文件格式');
    target.value = '';
  }
};

// 导出功能
const handleExport = async () => {
  try {
    const data = await StorageManager.getAll();

    // 创建导出数据
    const exportData = {
      prompts: data.prompts,
      categories: data.categories,
      exportTime: new Date().toISOString(),
      version: '1.0'
    };

    // 创建下载链接
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json'
    });
    const url = URL.createObjectURL(blob);

    // 创建下载元素
    const a = document.createElement('a');
    a.href = url;
    a.download = `prompts-export-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    // 清理URL对象
    URL.revokeObjectURL(url);

    message.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  }
};

const addCategory = async () => {
  if (!newCategoryName.value.trim()) {
    message.warning('请输入分类名称');
    return;
  }

  try {
    await StorageManager.addCategory({
      name: newCategoryName.value.trim(),
      color: 'blue',
      order: categories.value.length
    });
    await loadData();
    newCategoryName.value = '';
    message.success('分类添加成功');
  } catch (error) {
    console.error('添加分类失败:', error);
    message.error('添加分类失败');
  }
};

const deleteCategory = (categoryId: string) => {
  const category = categories.value.find(c => c.id === categoryId);
  if (!category) return;
  
  Modal.confirm({
    title: '删除确认',
    content: `确定要删除分类 "${category.name}" 吗？`,
    onOk: async () => {
      try {
        await StorageManager.deleteCategory(categoryId);
        await loadData();
        message.success('分类删除成功');
      } catch (error) {
        console.error('删除分类失败:', error);
        message.error('删除分类失败');
      }
    },
    onCancel: () => {
      // 用户取消删除，无需操作
    }
  });
};

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
};

// 生命周期
onMounted(() => {
  loadData();

  // 监听来自 background script 的消息
  browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'SHOW_VARIABLE_MODAL') {
      handleShowVariableModal(message.data);
      sendResponse({ success: true });
    }
    return true;
  });
});

// 处理显示变量输入模态框
const handleShowVariableModal = async (data: any) => {
  const { prompt, shortcutStartPos, shortcutEndPos } = data;

  try {
    const variables = extractVariables(prompt.content);

    if (variables.length > 0) {
      // 设置当前提示词和位置信息
      selectedPrompt.value = prompt;
      currentVariables.value = variables.map(name => ({
        name,
        value: '',
        placeholder: `请输入 ${name} 的值`
      }));

      // 存储替换位置信息
      (selectedPrompt.value as any).replaceInfo = {
        startPos: shortcutStartPos,
        endPos: shortcutEndPos
      };

      showVariableModal.value = true;

      // 聚焦第一个输入框
      await nextTick();
      const firstInput = document.querySelector('.ant-modal .ant-input') as HTMLInputElement;
      if (firstInput) {
        firstInput.focus();
      }
    } else {
      // 没有变量，直接替换
      const finalContent = prompt.content;
      browser.runtime.sendMessage({
        type: 'REPLACE_TEXT',
        data: {
          startPos: shortcutStartPos,
          endPos: shortcutEndPos,
          text: finalContent
        }
      });
    }
  } catch (error) {
    console.error('处理变量输入模态框失败:', error);
    message.error('处理失败');
  }
};
</script>

<style scoped>
.sidepanel-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.layout {
  height: 100%;
}

.header {
  background: #fff;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  height: auto;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  border-radius: 6px;
}

.add-btn {
  border-radius: 6px;
}

.search-bar {
  width: 100%;
}

.search-input {
  border-radius: 6px;
}

.content {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
}

.category-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.category-tag {
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.category-tag:hover {
  transform: translateY(-1px);
}

.prompts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.prompt-card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.prompt-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.prompt-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.prompt-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
}

.prompt-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.prompt-card:hover .prompt-actions {
  opacity: 1;
}

.prompt-content {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.prompt-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.footer {
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 12px 16px;
  height: auto;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.shortcut-hint {
  font-size: 12px;
  color: #6b7280;
}

.variables-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.settings-hint {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.import-export-section {
  margin: 16px 0;
}

.import-export-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
}

.import-export-btn {
  flex: 1;
}

.category-management {
  margin-top: 16px;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f9fafb;
  border-radius: 6px;
}

.add-category {
  display: flex;
  gap: 8px;
}

.add-category .ant-input {
  flex: 1;
}
</style>